
#import "PywPassportUtils.h"
#import "PywResourceUtils.h"
#import "PywMBProgressHUD+Pyw.h"

#define passportPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"yiavDZ@FU"]

@implementation PywPassportUtils

+ (void)savePassport:(PywUser *)user {
    if (user == nil) {
        return;
    }
    NSArray *userArray = [NSKeyedUnarchiver unarchiveObjectWithFile:passportPath];
    NSMutableArray *array = [NSMutableArray arrayWithArray:userArray];
    int i = 0;
    for (PywUser *myuser in userArray) {
        if ([myuser.passport isEqualToString:user.passport]) {
            [array removeObject:myuser];
//            [array addObject:user];
            [array insertObject:user atIndex:0];
            i = 1;
            break;
        }
    }
    // TODO:未完
    if (i == 0) {
//        [array addObject:user];
        [array insertObject:user atIndex:0];
    }

    if (array.count > 5) {
        [array removeLastObject];
    }
    
    [NSKeyedArchiver archiveRootObject:array toFile:passportPath];
}

+ (void)savePassportList:(NSArray *)array {
    [NSKeyedArchiver archiveRootObject:array toFile:passportPath];
}

+ (NSArray *)passport {
    return [NSKeyedUnarchiver unarchiveObjectWithFile:passportPath];
}

+ (BOOL)checkPassport:(NSString *)passport toview:(UIView *)view {
    if (passport.length < 6 || passport.length > 16) {
        [PywMBProgressHUD showError:@"用户名必须为6-12个字符" toView:view];
        return NO;
    }
    
    NSString *regex = @"^[a-zA-Z][a-zA-Z0-9]*$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isValid = [predicate evaluateWithObject:passport];
    if (!isValid) {
        [PywMBProgressHUD showError:@"用户名不合法" toView:view];
    }
    return isValid;
}

+ (BOOL)checkPassword:(NSString *)password toview:(UIView *)view {
    if (password.length < 6) {
        
        [PywMBProgressHUD showError:@"密码不能少于6个字符" toView:view];
        
        return NO;
    }
    
    NSString *regex = @"";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isValid = [predicate evaluateWithObject:password];
        if (!isValid) {
        [PywMBProgressHUD showError:@"密码不合法" toView:view];
    }
    return isValid;
}

@end
